import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/inventorytransfer/inventorytransfermodel.dart';
import 'package:opene/ui/inventorytransfer/lpnmapping/lpnmappingiblpnscreen.dart';
import 'package:toast/toast.dart';

class LpnMappingOBLpnScreen extends StatelessWidget {
  InventoryTransfer inventoryTransfer;

  LpnMappingOBLpnScreen({this.inventoryTransfer});

  @override
  Widget build(BuildContext context) {
    return LpnMappingOBLpnScreenPage(inventoryTransfer: inventoryTransfer);
  }
}

class LpnMappingOBLpnScreenPage extends StatefulWidget {
  InventoryTransfer inventoryTransfer;

  LpnMappingOBLpnScreenPage({this.inventoryTransfer});

  @override
  _LpnMappingOBLpnPageState createState() => _LpnMappingOBLpnPageState(inventoryTransfer: inventoryTransfer);
}

class _LpnMappingOBLpnPageState extends BaseState<LpnMappingOBLpnScreen> {
  InventoryTransfer inventoryTransfer;

  _LpnMappingOBLpnPageState({this.inventoryTransfer});

  List<Lpns> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Transfer:OBLPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    data = inventoryTransfer.lpns;
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "Trailer#: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                inventoryTransfer == null ? "" : Utils.getStringisEmpty(inventoryTransfer.trailerNumber),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "Outbound Date: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                inventoryTransfer == null ? "" : Utils.getStringisEmpty(inventoryTransfer.outboundDate),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "Success(OB/IB): ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                inventoryTransfer == null ? "" : "${Utils.getStringisInteger(inventoryTransfer.totalQty)}/${Utils.getStringisInteger(inventoryTransfer.completeQty)}",
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  inventoryCheckObLpn(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        inventoryCheckObLpn(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan or input outbound lpn",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Text(
            "Mapping Successfully",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 15),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        Lpns lpns = data[index];
        return Column(
          children: [
            Row(
              children: [
                Image.asset(
                  'assets/images/home/ic_transfer_oblpn.png',
                  width: 30,
                  height: 30,
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Column(
                    children: [
                      Text(
                        Utils.getStringisEmpty(lpns.obLpn),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                      Text(
                        Utils.getStringisEmpty(lpns.ibLpn),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void inventoryCheckObLpn(String obLpn) async {
    inventoryTransfer.obLpn = obLpn;

    Map<String, dynamic> map = new HashMap();
    map["trailerNumber"] = inventoryTransfer.trailerNumber;
    map["outboundDate"] = inventoryTransfer.outboundDate;
    map["obLpn"] = obLpn;
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.inventoryCheckObLpn, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => LpnMappingIBLpnScreen(inventoryTransfer: inventoryTransfer)),
      ).then((value) => {
            if ((value != null))
              {
                setState(() {
                  textEditingController.text = "";
                  inventoryTransfer =value;
                })
              }
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("please scan or input outbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    inventoryCheckObLpn(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
